package com.czy.seed.mvc.util;

import java.io.*;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;

import com.czy.seed.mvc.home.controller.MerchantController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * @Author: liuyun
 * Created by liuyun  10:25 2017/12/1.
 */
public class FilesUpload {
    public static Logger logger = LoggerFactory.getLogger(FilesUpload.class);

    public String Upload(String fileName,  String url, MultipartHttpServletRequest multiReq,String name) throws ServletException, IOException {
        // 获取上传文件的路径
        String uploadFilePath = multiReq.getFile(fileName).getOriginalFilename();
        // 截取上传文件的文件名
        String uploadFileName = uploadFilePath.substring(uploadFilePath.lastIndexOf('\\') + 1, uploadFilePath.indexOf('.'));

        // 截取上传文件的后缀
        String uploadFileSuffix = uploadFilePath.substring(uploadFilePath.indexOf('.') + 1, uploadFilePath.length());
        logger.info("=====开始上传文件名为：{}的文件信息", uploadFileName+"."+uploadFileSuffix);
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            fis = (FileInputStream) multiReq.getFile("file").getInputStream();
            if(name!= null){
                uploadFileName = name;
            }
            File file = new File(url+"\\" + uploadFileName + ".");
            fos = new FileOutputStream(file + uploadFileSuffix);
            byte[] temp = new byte[1024];
            int i = fis.read(temp);
            while (i != -1) {
                fos.write(temp, 0, temp.length);
                fos.flush();
                i = fis.read(temp);
            }
        } catch (IOException e) {
            logger.info("=====上传文件名为：{}的文件信息失败！，失败原因{}", uploadFileName, e);

        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    logger.info("=====上传文件名为：{}的文件信息失败！，失败原因{}", uploadFileName, e);
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    logger.info("=====上传文件名为：{}的文件信息失败！，失败原因{}", uploadFileName, e);
                }
            }
        }
        return uploadFileName+"."+uploadFileSuffix;
    }


}
